package com.test.web.base;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.filter.OrderedRequestContextFilter;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 登录检查
 * 
 * @author Robin.Wang
 * @date 2019-10-30
 */
@Slf4j
@Component
public class CheckFilter extends OrderedRequestContextFilter implements InitializingBean {

	@Value("${bsf.flow.user.logincheck.excludes:}")
	private String[] excludePaths;
	@Value("${bsf.flow.user.logincheck.adminpages:}")
	private String[] adminPages;

	@Override
	public int getOrder() {
		return -1;
	}

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		if (!this.isExcludePath(request)) {
			if(User.getCurrent()!=null)
			{
				filterChain.doFilter(request, response);
			} else {
				 request.getRequestDispatcher("/login").forward(request, response);
			}
		} else {
			filterChain.doFilter(request, response);
		}
	}

	boolean isExcludePath(HttpServletRequest request) {
		if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
			return true;
		} else if (this.excludePaths != null && this.excludePaths.length>0) {
			String path = request.getRequestURI();
			String context = request.getContextPath();
			if (context != null && context.length() > 0) {
				path = path.substring(context.length());
			}
			String[] var4 = this.excludePaths;
			for (int i = 0; i < var4.length; i++) {
				String exclude = var4[i];
				if (path.indexOf(exclude) > -1) {
					return true;
				}
			}
			return false;
		} 
		return false;
	}

}